package cn.globalph.housekeeper.ui.dialog;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import cn.globalph.housekeeper.R;
import cn.globalph.housekeeper.service.UpdateService;


public class DownLoaderDialog extends DialogFragment {
    ProgressBar progressBar;
    TextView percentTv;
    TextView backgroundDownloadTv;

    Handler handler = new Handler();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_download,container,false);
        progressBar = view.findViewById(R.id.progress);
        percentTv = view.findViewById(R.id.percent_tv);
        backgroundDownloadTv = view.findViewById(R.id.background_tv);
        backgroundDownloadTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(isVisible() && progressBar!=null && percentTv!=null){
                    progressBar.setProgress(UpdateService.pro);
                    percentTv.setText(UpdateService.pro+"%");
                }
                handler.postDelayed(this,1000);
            }
        },1000);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setLayout(dp2px(300), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    public int dp2px(float dpVal) {
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics()));
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (manager.isDestroyed()) {
                return;
            }
        }
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitAllowingStateLoss();
    }
}
